import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  message,
  Modal,
  Popconfirm,
  Row,
  Select,
  Spin,
  Table,
  Tooltip,
  DatePicker,
  Upload,
  Icon,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { FormattedMessage } from 'umi/locale';
import APP from '@/components/Tool/BaseAPP';

/**
 * 分页参数
 * @Author 肖家添
 * @Date 2019/8/22 15:09
 */
let pagingData = {
  _pageSize: 10,
  _current: 1,
  _total: 0,
};
const Dragger = Upload.Dragger;
@connect(({ appUpModel }) => ({
  appUpModel,
}))
@Form.create()
class AppUp extends Component {
  state = {
    loading: false,
    pageDataSource: [],
    selectedKeys: [],
    isShowEditModal: false,
    selectedFile: null,
  };

  componentDidMount() {
    this.findPageDataSource();
  }

  findPageDataSource = e => {
    let that = this,
      params = { ...pagingData };
    if (e) {
      pagingData._current = 1;
      e.preventDefault();
    }
    const { form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      APP.validNilParams(values);
      params = { ...params, ...values };
      requestContinue();
    });

    function requestContinue() {
      const { dispatch } = that.props;
      APP.loading(that);
      dispatch({
        type: 'appUpModel/list',
        payload: params,
        callback: function(data) {
          APP.closeLoading(that);
          if (data.success) {
            const { list, pagination } = data.datas;
            pagingData._current = pagination.current;
            pagingData._pageSize = pagination.pageSize;
            pagingData._total = pagination.total;
            that.setState({
              pageDataSource: list,
              selectedKeys: [],
            });
          }
        },
      });
    }
  };

  enabledControl = isEnabled => {
    const { selectedKeys } = this.state;
    if (selectedKeys <= 0) return;
    const that = this,
      { dispatch } = this.props;
    APP.loading(that);
    dispatch({
      type: 'appUpModel/enabledControl',
      payload: {
        ids: selectedKeys.join(','),
        isEnabled: isEnabled,
      },
      callback: function(data) {
        APP.closeLoading(that);
        if (data.success) {
          message.success('操作成功');
          that.findPageDataSource();
        } else {
          message.error('操作失败！');
        }
      },
    });
  };

  render() {
    const { loading, pageDataSource, selectedKeys } = this.state;
    const { form } = this.props;
    const that = this;
    const { getFieldDecorator } = form;
    return (
      <Spin spinning={loading}>
        <PageHeaderWrapper title={<FormattedMessage id="menu.appUp" />}>
          <Card style={{ marginBottom: 15 }}>
            <Form layout="inline" onSubmit={this.findPageDataSource}>
              <Row>
                <Col span={8}>
                  <Form.Item label="App名称">
                    {getFieldDecorator(
                      'aname',
                      {},
                    )(<Input placeholder="请输入App名称" allowClear={true} />)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="版本号">
                    {getFieldDecorator(
                      'versionNum',
                      {},
                    )(<Input placeholder="请输入版本号" allowClear={true} />)}
                  </Form.Item>
                </Col>
                  <Col span={8}>
                      <Form.Item label="App类型">
                          {getFieldDecorator(
                              'appType',
                              {},
                          )(<Select placeholder="请选择App类型" allowClear={true} style={{width: 220}}>
                              <Select.Option value={1}>议峰-光传</Select.Option>
                              <Select.Option value={2}>议峰智播</Select.Option>
                              <Select.Option value={3}>议峰-师傅端</Select.Option>
                              <Select.Option value={0}>其他</Select.Option>
                          </Select>)}
                      </Form.Item>
                  </Col>
              </Row>
              <Row>
                <Col
                  style={{ textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20 }}
                >
                  <Button type="primary" htmlType="submit" {...APP.buttonsStyle_MR15}>
                    查找
                  </Button>
                </Col>
              </Row>
            </Form>
          </Card>
          <Card style={{ marginBottom: 15 }}>
            <Button
              type="primary"
              {...APP.buttonsStyle_MR15}
              onClick={() => {
                this.setState({ isShowEditModal: true });
              }}
            >
              上传
            </Button>
            <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
              <Popconfirm
                title="确定删除选中数据吗？"
                onConfirm={() => {
                  this.enabledControl(-1);
                }}
                okText="删除"
                cancelText="取消"
                disabled={!(selectedKeys.length > 0)}
              >
                <Button type="primary" {...APP.buttonsStyle_MR15}>
                  删除
                </Button>
              </Popconfirm>
            </Tooltip>
          </Card>
          <Card>
            <Table
              bordered
              rowKey={data => `${data.id}`}
              rowSelection={APP.tableRowSelection(function(selectedRowKeys, selectedRows) {
                that.setState({ selectedKeys: selectedRowKeys });
              }, selectedKeys)}
              columns={this.columns}
              dataSource={pageDataSource}
              pagination={{
                pageSize: pagingData._pageSize,
                current: pagingData._current,
                total: pagingData._total,
                onChange: (page, pageSize) => {
                  pagingData._current = page;
                  this.findPageDataSource();
                },
                  showTotal: total => `共 ${total} 条数据`,
              }}
            />
          </Card>
          <EditForm parent={this} />
        </PageHeaderWrapper>
      </Spin>
    );
  }

  columns = [
    {
      title: 'App名称',
      dataIndex: 'aname',
      key: 'aname',
    },
      {
          title: 'App类型',
          dataIndex: 'appType',
          key: 'appType',
      },
    {
      title: '包名',
      dataIndex: 'packageName',
      key: 'packageName',
    },
    {
      title: '版本号',
      dataIndex: 'versionNum',
      key: 'versionNum',
    },
    {
      title: '更新方式',
      dataIndex: 'utype',
      key: 'utype',
    },
    {
      title: 'App文件地址',
      dataIndex: 'appPath',
      key: 'appPath',
    },
    {
      title: '开始更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
    {
      title: '更新内容',
      dataIndex: 'upcontent',
      key: 'upcontent',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
  ];

  fileUpload = (file, formType, callback, failCallback) => {
    const thisCtx = this;
    const { dispatch } = this.props;
    const formData = new window.FormData();
    formData.append('file', file);
    formData.append('formType', formType);
    dispatch({
      type: 'commonModel/fileUploadOfText',
      payload: formData,
      callback: function(data) {
        if (!data.success) {
          APP.errorMessage(thisCtx, '文件上传失败');
          failCallback();
        } else {
          if (APP.isValidObj(callback)) {
            callback(data);
          } else APP.closeLoading();
        }
      },
    });
  };
}

const EditForm = Form.create()(props => {
  let { parent, form } = props;
  const { dispatch } = parent.props;
  const { loading, isShowEditModal, selectedFile } = parent.state;
  const formItemLayout = {
    style: {
      margin: '0px',
    },
  };
  const { getFieldDecorator } = form;

  //-- 显示/隐藏 数据编辑窗口
  function handlerEditModal() {
    form.resetFields();
    let { isShowEditModal } = parent.state;
    isShowEditModal = !isShowEditModal;
    parent.setState({ isShowEditModal });
  }

  const colFloatRight = {
    style: {
      float: 'right',
    },
  };
  function submit() {
    form.validateFields((err, values) => {
      if (err) return;
      APP.validNilParams(values);
      values.updateTime = APP.momentFormatToStr(values.updateTime, 'YYYY-MM-DD HH:mm:ss');
      const { selectedFile } = parent.state;
      if (selectedFile) {
        APP.loading(parent);
        parent.fileUpload(selectedFile.originFileObj, 10002, function(data) {
          values.appPath = data.datas.filePath;
          request(values);
          APP.closeLoading(parent);
        });
      } else request(values);
    });

    function request(params) {
      APP.loading(parent);
      dispatch({
        type: 'appUpModel/saveAppUp',
        payload: params,
        callback: function(data) {
          APP.closeLoading(parent);
          if (data.success) {
            message.success('上传成功！');
            parent.findPageDataSource();
            handlerEditModal();
          } else {
            message.error(data.msg);
          }
        },
      });
    }
  }
  const uploadHandler = {
    accept: '.apk',
    showUploadList: false,
    //-- 上传前检测文件
    beforeUpload: function(file) {
      //-- 文件大小检测
      const checkFileSize = file.size / 1024 / 1024 < 1024;
      if (!checkFileSize) {
        message.error('文件必须小于1024MB!');
        return false;
      }
      if (['application/vnd.android.package-archive'].indexOf(file.type) === -1) {
        message.error('文件格式不正确!');
        return false;
      }
      return true;
    },
    onChange: function(info) {
      let status = info.file.status;
      if (status === 'uploading') return;
      if (['application/vnd.android.package-archive'].indexOf(info.file.type) === -1) return;
      APP.getImageFileBase64(info.file.originFileObj, image => {
        info.file.base64 = image;
        console.log(info.file);
        parent.setState({ selectedFile: info.file });
      });
    },
  };
  return (
    <Modal
      title={<FormattedMessage id="menu.appUp.addAppUp" />}
      visible={isShowEditModal}
      onOk={() => submit()}
      onCancel={() => handlerEditModal()}
      okText="上传"
      cancelText="关闭"
      confirmLoading={loading}
    >
      <Form layout="vertical">
        <Row>
          <Col span={11}>
            <Form.Item label="App名称" {...formItemLayout}>
              {getFieldDecorator('aname', {
                rules: [
                  {
                    required: true,
                    message: '请输入App名称！',
                  },
                ],
              })(<Input placeholder="请输入App名称" allowClear={true} />)}
            </Form.Item>
          </Col>
          <Col span={11} {...colFloatRight}>
            <Form.Item label="版本号" {...formItemLayout}>
              {getFieldDecorator('versionNum', {
                rules: [
                  {
                    required: true,
                    message: '请输入版本号！',
                  },
                ],
              })(<Input placeholder="请输入版本号" allowClear={true} />)}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={11}>
            <Form.Item label="包名称" {...formItemLayout}>
              {getFieldDecorator('packageName', {
                rules: [
                  {
                    required: true,
                    message: '请输入包名称！',
                  },
                ],
              })(<Input placeholder="请输入包名称" allowClear={true} />)}
            </Form.Item>
          </Col>
            <Col span={11} {...colFloatRight}>
                <Form.Item label="App类型" {...formItemLayout}>
                    {getFieldDecorator('appType', {
                        initialValue: 1,
                        rules: [
                            {
                                required: true,
                                message: '请选择App类型！',
                            },
                        ],
                    })(
                        <Select placeholder="请选择App类型">
                            <Select.Option value={1}>议峰-光传</Select.Option>
                            <Select.Option value={2}>议峰智播</Select.Option>
                            <Select.Option value={3}>议峰-师傅端</Select.Option>
                            <Select.Option value={0}>其他</Select.Option>
                        </Select>
                    )}
                </Form.Item>
            </Col>
        </Row>
        <Row>
          <Col span={11}>
            <Form.Item label="开始更新时间" {...formItemLayout}>
              {getFieldDecorator('updateTime', {
                rules: [
                  {
                    required: true,
                    message: '请输入开始更新时间！',
                  },
                ],
              })(<DatePicker placeholder="请输入开始更新时间" allowClear={true} showTime />)}
            </Form.Item>
          </Col>
          <Col span={11} {...colFloatRight}>
            <Form.Item label="更新方式" {...formItemLayout}>
              {getFieldDecorator('utype', {
                initialValue: 1,
                rules: [
                  {
                    required: true,
                    message: '请选择更新方式！',
                  },
                ],
              })(
                <Select placeholder={'请选择更新方式'}>
                  <Select.Option value={1}>静默更新</Select.Option>
                  <Select.Option value={2}>手动更新</Select.Option>
                </Select>,
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Form.Item label="App文件" {...formItemLayout}>
            {getFieldDecorator('appPath', {
              rules: [
                {
                  required: true,
                  message: '请上传App文件！',
                },
              ],
            })(
              <Dragger {...uploadHandler}>
                <p className="ant-upload-drag-icon">
                  <Icon type="inbox" />
                </p>
                <p className="ant-upload-text">点击或将文件拖拽到此区域上传</p>
              </Dragger>,
            )}
          </Form.Item>
        </Row>
        {APP.isValidObj(selectedFile) ? (
          <Row>
            <Form.Item label="文件名" {...formItemLayout}>
              <Input value={selectedFile.name} readOnly />
            </Form.Item>
          </Row>
        ) : (
          ''
        )}
        <Row>
          <Form.Item label="更新内容" {...formItemLayout}>
            {getFieldDecorator(
              'upcontent',
              {},
            )(
              <Input.TextArea
                placeholder="请输入更新内容"
                className="custom"
                style={{
                  height: 150,
                  width: '100%',
                  resize: 'none',
                }}
              />,
            )}
          </Form.Item>
        </Row>
      </Form>
    </Modal>
  );
});

export default AppUp;
